package com.ibix.dao;

import java.sql.*;

//用途是jdbc连接数据库
// 首相链接数据库  让后添加增加和删除操作

/* 项目要正常启动需要 1.配置好Tomcat 2.数据库地址名字是否正确 3.Tomcat里面需要添加mysql-connector-java-5.1.45-bin Mysql的驱动 */
public class BaseDao {

    // 数据库驱动
    public static final  String DRIVER = "com.mysql.jdbc.Driver";
    // 数据库地址
    public static final  String URL = "jdbc:mysql://localhost:3306/ImageProcessing";
    public static final  String USER = "";
    public static final String PASSWORD = "";

    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    // 链接数据库
    public void getConnection() {
        try {
            /* 加载驱动 DriverManager*/
//            com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver;
            Class.forName(DRIVER);
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 更新数据库
    public int updateUser(String sql,Object... obj){
        int num = 0;
        getConnection();
        try {
            pstmt =  connection.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++){
                pstmt.setObject(i + 1,obj[i]);
            }
            num = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return num;
    }

    // 查询
    public ResultSet executeQuery(String sql,Object... obj) {
        getConnection();
        try {
            pstmt = connection.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                pstmt.setObject(i + 1, obj[i]);
            }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public void closeAll(){
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
